//
//  LoginViewController.m
//  赶大集卖家版
//
//  Created by 王天义 on 16/9/26.
//  Copyright © 2016年 TYWang. All rights reserved.
//

#import "LoginViewController.h"
#import "RuZhuViewController.h"
#import "RootViewController.h"
#import "LoginNAVC.h"

@interface LoginViewController ()<UITextFieldDelegate>
@property(assign, nonatomic) NSInteger timeCount;
@property(strong, nonatomic) NSTimer *timer;
//@property (nonatomic , strong)   UITabBarController *tabBar;
//验证码
@property(copy, nonatomic) NSString *smsId;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    
    [self creatUI];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //    UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    //    //获取Main.storyboard中的首页
    //    _tabBar = [mainStory instantiateViewControllerWithIdentifier:@"mainVC"];
    self.navigationController.navigationBarHidden = YES;
    
    
}
#pragma mark - 设置UI
- (void)creatUI{
    
    UILabel *leftViewLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
    self.phoneTF.leftViewMode = UITextFieldViewModeAlways;
    self.phoneTF.leftView = leftViewLabel1;
    self.phoneTF.delegate = self;
    UILabel *leftViewLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
    self.yanZhengTF.leftViewMode = UITextFieldViewModeAlways;
    self.yanZhengTF.leftView = leftViewLabel2;
    self.yanZhengTF.delegate = self;
    //获取验证码按钮
    [self.getYanZhengBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.getYanZhengBtn setTitleColor:GDJGreenColor forState:UIControlStateNormal];
    [self.getYanZhengBtn addTarget:self action:@selector(getValidCode:) forControlEvents:UIControlEventTouchUpInside];
    self.getYanZhengBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    //登录按钮
    self.loginBtn.layer.cornerRadius = 10.0;
    [self.loginBtn addTarget:self action:@selector(loginCheck) forControlEvents:UIControlEventTouchUpInside];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    
    return YES;
}
#pragma mark - 判断手机号获取验证码请求
- (void)getValidCode:(UIButton *)sender
{
    if (![RegularExpressions validateMobile:self.phoneTF.text]) {
        
        //手机号不正确
        [self createAlertControllerWithMessage:@"手机号不正确" withState:1];
        
    }else{
        //手机号正确
        
        NSDictionary *param = @{@"ShouJiHao":self.phoneTF.text,@"Duuid":GETUUID};
        [GDJHttpTool get:SendCode params:param success:^(id responseObj) {
            NSLog(@"=========%@",responseObj);
            NSInteger err = [[responseObj valueForKey:@"Err"]integerValue];
        
            if (err == 999) {
             [SVProgressHUD showErrorWithStatus:@"发送失败" ];
            }
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
        }];
        sender.userInteractionEnabled = NO;
        self.timeCount = 60;
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(reduceTime:) userInfo:sender repeats:YES];
    }
}
#pragma mark - 验证码状态
- (void)reduceTime:(NSTimer *)codeTimer {
    self.timeCount--;
    if (self.timeCount == 0) {
        [self.getYanZhengBtn setTitle:@"重新获取验证码" forState:UIControlStateNormal];
        
        UIButton *info = codeTimer.userInfo;
        info.enabled = YES;
        self.getYanZhengBtn.userInteractionEnabled = YES;
        [self.timer invalidate];
        
    } else {
        NSString *str = [NSString stringWithFormat:@"%lu秒后重新获取", (long)self.timeCount];
        [self.getYanZhengBtn setTitle:str forState:UIControlStateNormal];
        self.getYanZhengBtn.backgroundColor = [UIColor grayColor];
        self.getYanZhengBtn.userInteractionEnabled = NO;
        
    }
}
#pragma mark - 登录按钮
- (void)loginCheck{
    NSLog(@"%@",GETUUID);
    NSLog(@"可可可可可可 手机号%@ token：%@ uuid：%@ cid：%@",GETPHONE,GETTOKEN,GETUUID,[NNSingleton sharedSingleton].CID);
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    NSString * isCID_String = [user objectForKey:REMEMBER_CID];
    NSLog(@"登陆登陆  cid%@",isCID_String);

    if (self.phoneTF.text.length > 0 && self.phoneTF.text.length > 0) {
        UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        //获取Main.storyboard中的首页
        RootViewController  *tabBar = [mainStory instantiateViewControllerWithIdentifier:@"mainVC"];
        [GDJHttpTool get:RegisterUser params:@{@"ShouJiHao":self.phoneTF.text,@"YanZhengMa":self.yanZhengTF.text,@"Duuid":GETUUID,@"PushID":isCID_String}  success:^(id responseObj) {
            NSLog(@"====%@",responseObj );
            //查看错误码
            NSInteger err = [[responseObj valueForKey:@"Err"]integerValue];
            NSLog(@"登陆----%@",responseObj[@"ErrMsg"]);
            if (err == 0) {
                [[NSUserDefaults standardUserDefaults]setObject:_phoneTF.text forKey:@"phoneNum"];
                [[NSUserDefaults standardUserDefaults]setObject:[responseObj valueForKey:@"Token"] forKey: @"Token"];
                [UIApplication sharedApplication].keyWindow.rootViewController = tabBar;
            }else if (err == 110||err == 112){
                [[NSUserDefaults standardUserDefaults]setObject:_phoneTF.text forKey:@"phoneNum"];
                [[NSUserDefaults standardUserDefaults]setObject:[responseObj valueForKey:@"Token"] forKey: @"Token"];
                RuZhuViewController *vc = [[RuZhuViewController alloc]init];
                LoginNAVC *naVC = [[LoginNAVC alloc] initWithRootViewController:vc];
                self.view.window.rootViewController = naVC;
                
                [SVProgressHUD  showWithStatus:[responseObj objectForKey:@"ErrMsg"]];
                [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
            }else{
                [SVProgressHUD  showWithStatus:[responseObj objectForKey:@"ErrMsg"]];
                [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
            }
        } failure:^(NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
}
#pragma mark - 提示框
- (void)createAlertControllerWithMessage:(NSString *)message withState:(NSInteger )state{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //0.
        if (state == 0) {
            
        } //1.清空手机号
        else if (state == 1){
            //            self.phoneText.text = nil;
            
        } //2.清空验证码
        else if (state == 2){
            //            self.yanzhengmaText.text = nil;
        }
    }];
    
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
}
- (void)dismiss{
    [SVProgressHUD dismiss];
}
@end
